//
//  CategoryView.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import SwiftUI
import UIKit

struct CategoryView: View {
    @StateObject private var viewModel = CategoryViewModel()
    @State private var selectedCategoryIndex = 0
    
    var body: some View {
        VStack(spacing: 0) {
            // 搜索栏
            CategorySearchBarView()
            
            // 主要内容区域
            HStack(spacing: 0) {
                // 左侧分类列表
                VStack(spacing: 0) {
                    ScrollView {
                        LazyVStack(spacing: 0) {
                            ForEach(Array(viewModel.categories.enumerated()), id: \.element.id) { index, category in
                                CategoryItemView(
                                    category: category,
                                    isSelected: index == selectedCategoryIndex
                                )
                                .onTapGesture {
                                    selectedCategoryIndex = index
                                }
                            }
                        }
                    }
                }
                .frame(width: 100)
                .background(Color(.systemGray6))
                
                // 右侧子分类内容
                VStack(spacing: 0) {
                    if selectedCategoryIndex < viewModel.categories.count {
                        let selectedCategory = viewModel.categories[selectedCategoryIndex]
                        
                        ScrollView {
                            LazyVStack(spacing: 16) {
                                if let children = selectedCategory.children {
                                    ForEach(children) { childCategory in
                                        SubCategoryView(category: childCategory)
                                    }
                                }
                            }
                            .padding(.horizontal, 16)
                            .padding(.top, 16)
                        }
                    }
                }
                .background(Color.white)
            }
        }
        .navigationBarHidden(true)
        .onAppear {
            Task {
                await viewModel.loadCategories()
            }
        }
    }
}

// MARK: - 搜索栏组件
struct CategorySearchBarView: View {
    @State private var searchText = ""
    
    var body: some View {
        HStack {
            HStack {
                Image(systemName: "magnifyingglass")
                    .foregroundColor(.gray)
                
                TextField("搜索商品", text: $searchText)
                    .textFieldStyle(PlainTextFieldStyle())
                
                if !searchText.isEmpty {
                    Button(action: {
                        searchText = ""
                    }) {
                        Image(systemName: "xmark.circle.fill")
                            .foregroundColor(.gray)
                    }
                }
            }
            .padding(.horizontal, 12)
            .padding(.vertical, 8)
            .background(Color(.systemGray6))
            .cornerRadius(20)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 8)
        .background(Color.white)
    }
}

// MARK: - 左侧分类项
struct CategoryItemView: View {
    let category: ProductCategory
    let isSelected: Bool
    
    var body: some View {
        VStack(spacing: 8) {
            Text(category.cateName)
                .font(.system(size: 14))
                .foregroundColor(isSelected ? ThemeHelper.shared.getColor() : .primary)
                .multilineTextAlignment(.center)
                .lineLimit(2)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 16)
        .background(isSelected ? Color.white : Color.clear)
        .overlay(
            Rectangle()
                .fill(ThemeHelper.shared.getColor())
                .frame(width: 3)
                .opacity(isSelected ? 1 : 0),
            alignment: .leading
        )
    }
}

// MARK: - 右侧子分类视图
struct SubCategoryView: View {
    let category: ProductCategory
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            // 分类标题
            HStack {
                Text(category.cateName)
                    .font(.headline)
                    .fontWeight(.semibold)
                
                Spacer()
            }
            
            // 子分类网格
            if let children = category.children {
                LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 16) {
                    ForEach(children) { subCategory in
                        SubCategoryItemView(category: subCategory)
                    }
                }
            }
        }
        .padding(16)
        .background(Color.white)
        .cornerRadius(12)
    }
}

// MARK: - 子分类项
struct SubCategoryItemView: View {
    let category: ProductCategory
    
    var body: some View {
        Button(action: {
            // 获取根视图控制器用于显示新页面
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                  let rootViewController = windowScene.windows.first?.rootViewController else {
                return
            }
            
            // 创建商品列表视图，包装在 NavigationView 中
            // 传递参数：cid=category.id, title=category.cateName
            let goodsListView = NavigationView {
                GoodsListView(categoryId: category.id, title: category.cateName)
            }
            let hostingController = UIHostingController(rootView: goodsListView)
            hostingController.modalPresentationStyle = .fullScreen
            rootViewController.present(hostingController, animated: true)
        }) {
            VStack(spacing: 8) {
                // 分类图标
                AsyncImage(url: URL(string: category.fullPicUrl)) { image in
                    image
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                } placeholder: {
                    RoundedRectangle(cornerRadius: 8)
                        .fill(Color.gray.opacity(0.3))
                        .overlay(
                            Image(systemName: "photo")
                                .foregroundColor(.gray)
                        )
                }
                .frame(width: 60, height: 60)
                .cornerRadius(8)
                
                // 分类名称
                Text(category.cateName)
                    .font(.caption)
                    .foregroundColor(.primary)
                    .lineLimit(1)
                    .multilineTextAlignment(.center)
            }
        }
        .buttonStyle(PlainButtonStyle())
    }
}

struct CategoryView_Previews: PreviewProvider {
    static var previews: some View {
        CategoryView()
    }
}
